import re

file = r'SP_out.txt'


class Data:
    def __init__(self, data, i):
        self.data = data.strip()
        self.symbol = ''
        self.mark = ''
        self.val = []
        self.f = ''
        self.i = i
        self.out = 0
        self.lock = 0
        self.lock_val = 0
        self.excep = 0
        # self.begin()

    def Symbol(self):  # 读取符号
        if self.data[0] == '&':
            self.symbol = '&'
        elif self.data[0:2] == '||':
            self.symbol = "||"
        else:
            print(f"第{self.i}行存在异常，无法读取到&或||符号")
            self.excep = 1

    def Mark(self):  # 读取目标端口
        # data = self.data.split(' ')
        mar = r'[A-Za-z]+[\w]*\.\s?[\w]+|[A-Za-z]+[\w]*[ []{2}[bit0-9]{4}[] ]{2}[\w]+|[A-Z]+[A-Za-z0-9_]{5,}'
        # 编译正则表达式读取标记端口 (   ).(   )
        """
        mar2 = r'[A-Za-z]+[\w]*[ []{2}[bit0-9]{4}[] ]{2}[\w]+'
        mar3 = r'[A-Za-z]+[\w]*[\w]+'
        """
        if re.findall(mar, self.data):
            self.mark = re.findall(mar, self.data)[0]
            self.mark = self.mark.replace(' [', '__', 1)
            self.mark = self.mark.replace('] ', '__', 1)
            self.mark = self.mark.replace(' ', '_')
            self.mark = self.mark.replace('.', '_')
        else:
            print(f"无法正确读取第{self.i}行数据端口")
            self.excep = 2
        # print(data)

    def comparsion(self):  # 读取符号
        if self.mark == '':
            return
        mar = r'[＜＞<>=!！≤≥]+'
        if re.findall(mar, self.data):
            self.f = re.findall(mar, self.data)
            f = str(self.f[0])
            f = f.replace('==', '=')
            f = f.replace('＜', '<')
            f = f.replace('＞', '>')
            f = f.replace('！', '!')
            self.f = f
        else:
            print(f"第{self.i}行无法找到正确的符号")
            self.excep = 3

    def Val(self):  # 读取数字
        if self.mark == '':
            return
        mar = r'[＜＞<>=!≤≥]+[-% 0-9x||.A-F~]+'
        lis = re.findall(mar, self.data)
        if lis:
            self.val = lis[0]
            self.val = self.val.replace(' ', '')
            self.val = self.val.replace('=', '')
            self.val = self.val.replace('!', '')
            self.val = self.val.replace('＜', '')
            self.val = self.val.replace('＞', '')
            self.val = self.val.replace('<', '')
            self.val = self.val.replace('>', '')
            self.val = self.val.replace('≤', '')
            self.val = self.val.replace('≥', '')
            self.val = self.val.replace('0x', '')
            self.val = self.val.split('||')
            if self.val[0].find('%') != -1:
                na = self.val[0]
                count = na.find('%')
                na = na[:count]
                na = int(na)
                na = na / 100.0
                self.val[0] = str(na)
            q = 0
            for na in self.val:
                if str(na).find('~') != -1:
                    count = na.find('~')
                    fir = int(na[:count], 16)
                    self.val[q] = str(fir)
                    end = int(na[count + 1:], 16)
                    while fir != end:
                        self.val.append(str(fir + 1))
                        fir = fir + 1
                q += 1
            for na in self.val:
                if na.isalpha():
                    na = int(na, 16)
                    self.val[0] = str(self.factor(na))
        else:
            print(f"第{self.i}行读取值错误")
            self.excep = 4

    def check_out(self):  # 读取端口、锁定值
        if self.excep == 2:
            return
        f = open(file, 'r', encoding='UTF-8')
        for z in f.readlines():
            if z.count(self.mark):
                q = z.find('(')
                p = z.find(',')
                self.out = z[q + 1:p]
                q = z.find('[')
                p = z.find(']')
                a = z[q + 1: p]
                p = a.find(',')
                self.lock = a[:p]
                self.lock_val = a[p + 1:]
                f.close()
                break
        if self.out == 0:
            self.excep = 5
            print(f"第{self.i}行参数  {self.mark}  无法读取正确端口")

    def begin(self):
        self.Symbol()
        self.Mark()
        self.Val()
        self.comparsion()
        self.check_out()
        if self.excep != 0:
            print(f"第{self.i}行存在异常")

    def printf(self):
        if self.excep == 0:
            print(self.symbol, self.mark, self.f, self.val, self.out)
            print(f"mark({self.out},:)\t=[{self.lock},{self.lock_val}]")

    def factor(self, num):
        mar = r'[fFactor: .0-9]{7,}[ ]*[-Oofset:.0-9]{7,}'
        off = re.findall(mar, self.data)
        if off:
            off = off[0]
            mar2 = r'[0-9.-]+'
            off = re.findall(mar2, off)
            if off:
                factor = float(off[0])
                offset = float(off[1])
                return num * factor + offset
            else:
                return num
        else:
            return num
